package com.xz.product.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.SecurityUtils;
import com.xz.common.utils.StringUtils;
import com.xz.product.domain.ProductAttributeParam;
import com.xz.product.dto.AttributeParamDto;
import com.xz.product.dto.ProductDto;
import com.xz.product.dto.ProductExportDto;
import com.xz.product.dto.ProductInfoDto;
import com.xz.product.service.IProductCategoryService;
import com.xz.product.service.IProductMeasuringUnitService;
import com.xz.product.vo.ProductCategoryVo;
import com.xz.product.vo.ProductImportVo;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.service.IPurchaseProductService;
import common.ECCalculateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xz.product.mapper.ProductMapper;
import com.xz.product.domain.Product;
import com.xz.product.service.IProductService;
import org.springframework.util.CollectionUtils;

/**
 * 商品Service业务层处理
 *
 * @author xz
 * @date 2024-01-02
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IProductMeasuringUnitService iProductMeasuringUnitService;
    @Autowired
    private IProductCategoryService iProductCategoryService;
    @Autowired
    private IPurchaseProductService iPurchaseProductService;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public ProductInfoDto selectProductById(Long id) {
        ProductInfoDto productInfoDto = productMapper.selectProductById(id);
        if(Objects.nonNull(productInfoDto)){
            productInfoDto.setIsPurchase(2);
            int count = iPurchaseProductService.count(new QueryWrapper<PurchaseProduct>().eq("product_id", id).eq("status", 1));
            if(count>0){
                productInfoDto.setIsPurchase(1);
            }
        }

        return productInfoDto;
    }

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<ProductDto> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }
    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<ProductExportDto> selectProductExport(Product product) {
        return productMapper.selectProductExport(product);
    }

    @Override
    public AjaxResult importExcel(List<ProductImportVo> importVoList) {
        List<Product> productList=new ArrayList<>();

        for(ProductImportVo productImportVo:importVoList){
            Product product=new Product();

            if(StringUtils.isEmpty(productImportVo.getSpecification())){
                return AjaxResult.error("规格不能为空");
            }
            product.setSpecification(productImportVo.getSpecification());
            product.setSeries(productImportVo.getSeries());
            product.setStatus("2");
            if(productImportVo.getPrice()==null){
                return AjaxResult.error("售价不能为空");
            }
            product.setPrice(productImportVo.getPrice());
            if(StringUtils.isEmpty(productImportVo.getManufacturer())){
                return AjaxResult.error("生产厂家不能为空");
            }
            product.setManufacturer(productImportVo.getManufacturer());
            if(StringUtils.isEmpty(productImportVo.getIsDevicesName())){
                return AjaxResult.error("医疗器械/非医疗器械不能为空");
            }
            product.setIsDevices("医疗器械".equals(productImportVo.getIsDevicesName())?1:2);
            product.setRegistrationNo(productImportVo.getRegistrationNo());
            try {
                product.setRegistrationValiddityDate(productImportVo.getRegistrationValiddityDate());
            }catch (Exception e){
                return AjaxResult.error("注册证有效期时间格式有误，请修参考【2024-01-01】进行填写");
            }
            if(StringUtils.isEmpty(productImportVo.getProductCategory())){
                return AjaxResult.error("商品类别不能为空");
            }
            Long categoryId = iProductCategoryService.getId(productImportVo.getProductCategory());
            product.setCategoryId(categoryId);
            if(StringUtils.isEmpty(productImportVo.getBrandName())){
                return AjaxResult.error("商品品牌不能为空");
            }
            String unitName = productImportVo.getUnitName();

            Long brandId = iProductMeasuringUnitService.getId(productImportVo.getBrandName(),3);
            product.setBrandId(brandId);
            if(StringUtils.isEmpty(productImportVo.getProdName())){
                return AjaxResult.error("产品名称不能为空");
            }
            Long prodNameId = iProductMeasuringUnitService.getId(productImportVo.getProdName(),2);
            product.setProdNameId(prodNameId);
            if(StringUtils.isEmpty(productImportVo.getUnitName())){
                return AjaxResult.error("计量单位不能为空");
            }
            Long unitId = iProductMeasuringUnitService.getId(productImportVo.getUnitName(),1);
            product.setUnitId(unitId);
            if(StringUtils.isEmpty(productImportVo.getProductName())){
                productImportVo.setProductName(productImportVo.getBrandName()+productImportVo.getProdName()+productImportVo.getSpecification()+(StringUtils.isEmpty(productImportVo.getSeries())?"":productImportVo.getSeries()));
            }
            product.setProductName(productImportVo.getProductName());
            product.setStatus("0");
            productList.add(product);
        }
        if(!CollectionUtils.isEmpty(productList)){
            productList.stream().forEach(i->{
                i.setEncoded(RedisCode.getCode("SP"));
            });
            boolean saveBatch = this.saveBatch(productList);
            if(saveBatch){
                return AjaxResult.success("导入成功");
            }
            return AjaxResult.error("导入失败");
        }

        return AjaxResult.error("导入失败");
    }

    /**
     * 新增商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public AjaxResult insertProduct(Product product) {
        //校验是否已经添加
        int count = this.count(new QueryWrapper<Product>().eq("product_name", product.getProductName()).eq("del_flag", 0));
        if(count>0){
            return AjaxResult.error("数据【"+product.getProductName()+"】已存在");
        }
        product.setEncoded(RedisCode.getCodeNoTime("SP"));
        product.setCreateTime(DateUtils.getNowDate());
        product.setCreateBy(SecurityUtils.getUserId());
        product.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        int insertProduct = productMapper.insertProduct(product);
        return insertProduct>0? AjaxResult.success("新增成功"):AjaxResult.error("新增失败");
    }

    /**
     * 修改商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public AjaxResult updateProduct(Product product) {
        if(product.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        //校验是否已经添加
        int count = this.count(new QueryWrapper<Product>().eq("product_name", product.getProductName()).eq("del_flag", 0).ne("id",product.getId()));
        if(count>0){
            return AjaxResult.error("数据【"+product.getProductName()+"】已存在");
        }
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(SecurityUtils.getUserId());
        int updateProduct = productMapper.updateProduct(product);
        return updateProduct>0? AjaxResult.success("修改成功"):AjaxResult.error("修改失败");
    }
    /**
     * 修改商品价格
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public AjaxResult updatePrice(Product product) {
        if(product.getId()==null){
            return AjaxResult.error("参数id不能为空");
        }
        product.setUpdateTime(DateUtils.getNowDate());
        product.setUpdateBy(SecurityUtils.getUserId());
        int updateProduct = productMapper.updateProduct(product);
        return updateProduct>0? AjaxResult.success("修改成功"):AjaxResult.error("修改失败");
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(Long[] ids) {
        return productMapper.deleteProductByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteProductById(Long id) {
        int deleteProductById = productMapper.deleteProductById(id);
        return deleteProductById>0?AjaxResult.success("删除成功"):AjaxResult.error("删除失败");
    }

    public static void main(String[] args) {
//        List<Double> list = DoubleStream.iterate(-10, n -> n + 0.26) .limit((long) ((10 - (-10)) / 0.26 + 1)) .boxed() .collect(Collectors.toList());
//        System.out.println(list);
        List<Integer> WaitPay = new ArrayList<>(Arrays.asList(1));

        /**
         * 销售处理
         */
        List<Integer> SalesProcessing = new ArrayList<>(Arrays.asList(2, 3));
        WaitPay.retainAll(SalesProcessing);
        System.out.println(WaitPay.size());

    }

    @Override
    public List<AttributeParamDto> getProductAttributeParamList(Long id) {
        List<AttributeParamDto> list=new ArrayList<>();
        List<ProductAttributeParam> productAttributeParamList = baseMapper.getProductAttributeParamList(id);
        if(!CollectionUtils.isEmpty(productAttributeParamList)){
            productAttributeParamList.stream().forEach(i->{
                if(Objects.nonNull(i)) {
                    AttributeParamDto attributeParamDto = new AttributeParamDto();
                    attributeParamDto.setAttributeName(i.getProductAttributeName());
                    attributeParamDto.setAttributeCategory(i.getAttributeCategory());
                    attributeParamDto.setIsInput(i.getIsInput());
                    attributeParamDto.setInputMode(i.getInputMode());
                    if (i.getInputMode() == 1) {
                        if (StringUtils.isNotBlank(i.getUpperLimit()) && StringUtils.isNotBlank(i.getLowerLimit()) && StringUtils.isNotBlank(i.getStep())) {
                            List<Double> doubleList = DoubleStream.iterate(Double.parseDouble(i.getLowerLimit()), n -> n + Double.parseDouble(i.getStep())).limit((long) ((Double.parseDouble(i.getUpperLimit()) - Double.parseDouble(i.getLowerLimit())) / Double.parseDouble(i.getStep()) + 1)).boxed().collect(Collectors.toList());
                            List<String> attributeParameter = new ArrayList<>();
                            doubleList.stream().forEach(j -> {
                                double round = ECCalculateUtils.round(j, 2);
                                boolean flag=false;
                                if(round>0){
                                    flag=true;
                                }
                                String modified = String.format("%.2f", Float.parseFloat(round+""));
                                if(i.getProductAttributeName().equals("柱镜") || i.getProductAttributeName().equals("球镜") ){
                                    attributeParameter.add(flag?"+"+modified:modified);
                                }else{
                                    attributeParameter.add(modified);
                                }
                            });
                            attributeParamDto.setAttributeParameter(attributeParameter);
                        }
                    } else {
                        if (StringUtils.isNotBlank(i.getTextParam())) {
                            List<String> attributeParameter = new ArrayList<>();

                            attributeParameter.addAll(Arrays.asList(i.getTextParam().split(",")));
                            attributeParamDto.setAttributeParameter(attributeParameter);
                        }
                    }
                    list.add(attributeParamDto);
                }
            });
        }

        return list;
    }

    @Override
    public Product getProductInfo(String encoded) {
        return baseMapper.getProductInfo(encoded);
    }

    /**
     * 获取商品属性
     * @param id
     * @return
     */
    @Override
    public ProductCategoryVo getProductCategory(Long id) {
        return baseMapper.getProductCategory(id);
    }
}
